// pages/index/index.js
import {
  calculateBazi
} from '../../utils/calendar.js';

Page({
  data: {
    birthday: '',
    birthTime: '12:00',
    showResult: false,
    bazi: {}
  },

  onLoad() {
    this.setData({
      birthday: this.getDefaultDate()
    });
  },

  getDefaultDate() {
    const date = new Date();
    return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`;
  },

  dateChange(e) {
    this.setData({
      birthday: e.detail.value
    });
  },

  timeChange(e) {
    this.setData({
      birthTime: e.detail.value
    });
  },

  calculate() {
    const {
      birthday,
      birthTime
    } = this.data;
    const bazi = calculateBazi(birthday, birthTime);

    this.setData({
      showResult: true,
      bazi: {
        ...bazi,
        analysis: this.getBaziAnalysis(bazi)
      }
    });
  },

  getBaziAnalysis(bazi) {
    const analysisMap = {
      // 八字解析数据
      '癸卯': '水兔之年，聪慧灵动',
      '戊午': '土火相生，热情稳重',
      '丙寅': '火木通明，积极进取',
      '甲午': '木火相生，才思敏捷'
    };

    return [
      `年柱 ${bazi.year}: ${analysisMap[bazi.year] || '根基深厚'}`,
      `月柱 ${bazi.month}: ${analysisMap[bazi.month] || '运势通达'}`,
      `日柱 ${bazi.day}: ${analysisMap[bazi.day] || '主运昌隆'}`,
      `时柱 ${bazi.hour}: ${analysisMap[bazi.hour] || '晚景丰裕'}`
    ];
  },

  getBirthEightCharacters() {

    const {
      birthday,
      birthTime
    } = this.data;
    console.info(birthday + birthTime)

    const [year, month, day] = birthday.split('-').map(Number);
    const hour = birthTime.split(":")[0];

    if (!year || !month || !day || hour === undefined) {
      wx.showToast({
        title: '请输入完整的出生日期和时辰',
        icon: 'none'
      });
      return;
    }
    const eightCharacters = this.calculateBirthEightCharacters(year, month, day, hour);
    console.info(eightCharacters)
    this.setData({
      showResult: true,
      bazi: {
        analysis: eightCharacters
      }
    });
  },

  calculateBirthEightCharacters(year, month, day, hour) {

    console.info("time - " + year + month + day + hour)
    const heavenlyStems = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'];
    const earthlyBranches = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
    const solarTerms = [
      '小寒', '大寒', '立春', '雨水', '惊蛰', '春分', '清明', '谷雨', '立夏', '小满', '芒种', '夏至',
      '小暑', '大暑', '立秋', '处暑', '白露', '秋分', '寒露', '霜降', '立冬', '小雪', '大雪', '冬至'
    ];
    // 获取年柱
    function getYearColumn(year) {
      const stemIndex = (year - 4) % 10;
      const branchIndex = (year - 4) % 12;
      return heavenlyStems[stemIndex] + earthlyBranches[branchIndex];
    }
    // 获取月柱（简化，未考虑节气精确计算）
    function getMonthColumn(year, month) {
      const baseStem = [5, 7, 9, 1, 3];
      const stemIndex = (baseStem[(year % 5)] + month - 1) % 10;
      const branchIndex = (month + 1) % 12;
      return heavenlyStems[stemIndex] + earthlyBranches[branchIndex];
    }
    // 简化的日柱计算（实际需更复杂算法或查万年历）
    function getDayColumn(year, month, day) {
      // if (month < 3) {
      //     month += 12;
      //     year--;
      // }
      // const c = Math.floor(year / 100);
      // const y = year % 100;
      // const m = month;
      // const d = day;
      // const w = c / 4 - 2 * c + y + y / 4 + 13 * (m + 1) / 5 + d - 1;
      // const wPositive = (w % 60 + 60) % 60;
      // const stemIndex = wPositive % 10;
      // const branchIndex = wPositive % 12;
      // return heavenlyStems[stemIndex] + earthlyBranches[branchIndex];
      // 1. 计算儒略日数（Julian Day Number）
      const a = Math.floor((14 - month) / 12);
      const y = year + 4800 - a;
      const m = month + 12 * a - 3;
      let jd = day + Math.floor((153 * m + 2) / 5) + 365 * y + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400) - 32045;

      // 2. 计算干支索引（基准：2000-01-01 的日柱为 "甲戌"，对应索引为 10）
      const offset = (jd - 2451545) + 10; // 2451545 是 2000-01-01 的儒略日数
      const ganZhiIndex = (offset % 60 + 60) % 60; // 确保索引为正数

      // 3. 获取天干地支
      const stemIndex = ganZhiIndex % 10;
      const branchIndex = ganZhiIndex % 12;
      return heavenlyStems[stemIndex] + earthlyBranches[branchIndex];
    }

    function getHourGanZhi(dayGanZhi, hour) {
      const dayStem = heavenlyStems.indexOf(dayGanZhi[0]);
      const branchIndex = Math.floor((hour + 1) / 2) % 12;
      const stemIndex = (dayStem * 2 + branchIndex) % 10;
      return heavenlyStems[stemIndex] + earthlyBranches[branchIndex];
    }
    // 获取时柱
    function getHourColumn(hour) {
      const hourMap = {
        23: 0,
        0: 0,
        1: 1,
        2: 1,
        3: 2,
        4: 2,
        5: 3,
        6: 3,
        7: 4,
        8: 4,
        9: 5,
        10: 5,
        11: 6,
        12: 6,
        13: 7,
        14: 7,
        15: 8,
        16: 8,
        17: 9,
        18: 9,
        19: 10,
        20: 10,
        21: 11,
        22: 11
      };
      const branchIndex = hourMap[hour];
      // 时柱天干需结合日柱天干计算，这里简化
      const stemIndex = 0;
      return heavenlyStems[stemIndex] + earthlyBranches[branchIndex];
    }
    const yearColumn = getYearColumn(year);
    const monthColumn = getMonthColumn(year, month);
    const dayColumn = getDayColumn(year, month, day);
    const hourColumn = getHourColumn(hour);
    // const hourColumn = getHourGanZhi(getDayColumn, hour);
    return `${yearColumn} ${monthColumn} ${dayColumn} ${hourColumn}`;
  }

});